package com.yint.core;

import java.io.IOException;

public abstract class AbsReactor implements Reactor {

	private volatile boolean isStart = false;

	/**
	 * 启动反应器
	 * 
	 */
	@Override
	public final synchronized void start() {
		if (!isStart()) {
			isStart = true;
			try {
				onStart();
				react();
			} catch (Exception e) {
				System.out.println("[Warning!] A client has been closed.");
				e.printStackTrace();
				stop();
			}
		}
	}

	protected void onStart() throws IOException {

	}

	/**
	 * 检测NIO 事件变化
	 * 
	 * @throws IOException
	 */
	private void react() throws IOException {
		while (isStart() && !Thread.interrupted()) {
			if(isKeepHandleing()) {
				handle();
			}
		}
	}

	protected abstract void handle() throws IOException;

	@Override
	public final synchronized void stop() {
		isStart = false;
		try {
			onStop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public final boolean isStart() {
		return isStart;
	}

	protected void onStop() {

	}

	private boolean isKeepHandleing() {
		return isHandleing();
	}

	protected boolean isHandleing() {
		return true;
	}
}
